package com.gitee.jiaojinxin.oauth2.auth.model;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetails;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 自定义客户端详情
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity(name = "my_client")
public class MyClient implements ClientDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    public String clientId;

    public String clientSecret;

    private String resourceIdStr;

    private String redirectUriStr;

    @Override
    public Set<String> getResourceIds() {
        return splitStr(resourceIdStr);
    }

    @Override
    public boolean isSecretRequired() {
        return StrUtil.isNotBlank(clientSecret);
    }

    @Override
    public boolean isScoped() {
        return CollUtil.isNotEmpty(getScope());
    }

    @Override
    public Set<String> getScope() {
        return new HashSet<>(Arrays.asList("read", "write"));
    }

    @Override
    public Set<String> getAuthorizedGrantTypes() {
        return new HashSet<>(Arrays.asList("authorization_code", "refresh_token"));
    }

    @Override
    public Set<String> getRegisteredRedirectUri() {
        return splitStr(redirectUriStr);
    }

    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        return Collections.emptyList();
    }

    @Override
    public Integer getAccessTokenValiditySeconds() {
        return 3600;
    }

    @Override
    public Integer getRefreshTokenValiditySeconds() {
        return 86400;
    }

    @Override
    public boolean isAutoApprove(String scope) {
        return false;
    }

    @Override
    public Map<String, Object> getAdditionalInformation() {
        return null;
    }

    private Set<String> splitStr(String str){
        Set<String> strs = new HashSet<>();
        if (StrUtil.isNotBlank(str)
                && str.split(",").length > 0) {
            for (String s : str.split(",")) {
                if (strs.contains(s)) {
                    continue;
                }
                strs.add(s);
            }
        }
        return strs;
    }
}
